package com.come4loves.game.module.battle.helper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.come4loves.core.comunicate.protocol.Response;
import com.come4loves.core.context.SpringContext;
import com.come4loves.game.module.battle.model.ActorCard;
import com.come4loves.game.module.battle.model.BattleData;
import com.come4loves.game.proto.BattleCmd;
import com.come4loves.game.proto.BattleProto;
import com.come4loves.game.proto.BattleProto.CardsInfo;
import com.come4loves.game.proto.ModuleName;
import com.come4loves.game.server.session.PlayerContext;

public class BattlePushHelper {
	public static void pushBattleData(long actorId, BattleData bd) {
		BattleProto.BattleDataResponse.Builder builder = BattleProto.BattleDataResponse.newBuilder();
		Map<Long, ActorCard> actorCards = bd.getActorCards();
		Set<Long> actorIds = actorCards.keySet();
		List<Long> temp = new ArrayList<Long>();
		temp.add(actorId);
		Iterator<Long> it = actorIds.iterator();
		while (it.hasNext()) {
			long id = it.next();
			if (id != actorId) {
				temp.add(id);
			}
		}
		
		for (long tmpId : temp) {
			ActorCard actorCard = actorCards.get(tmpId);
			BattleProto.BattleDataResponse.ActorCard.Builder actorCardBuilder = BattleProto.BattleDataResponse.ActorCard.newBuilder();
			actorCardBuilder.setActorId(tmpId);
			actorCardBuilder.setTeam(PBConvertHelper.teamConvert(actorCard.getTeam()));
			List<CardsInfo> sList = PBConvertHelper.fightCard2CardsInfo(actorCard.getStorageCards(), false);
			for (CardsInfo cardsInfo : sList) {
				actorCardBuilder.addStorageCards(cardsInfo);
			}
			if (actorId == tmpId) {
				sList = PBConvertHelper.fightCard2CardsInfo(actorCard.getHandsCards(), true);
			} else {
				sList = PBConvertHelper.fightCard2CardsInfo(actorCard.getHandsCards(), false);
			}
			for (CardsInfo cardsInfo : sList) {
				actorCardBuilder.addHandsCards(cardsInfo);
			}
			sList = PBConvertHelper.fightCard2CardsInfo(actorCard.getDeskCards(), true);
			for (CardsInfo cardsInfo : sList) {
				actorCardBuilder.addDeskCards(cardsInfo);
			}
			sList = PBConvertHelper.fightCard2CardsInfo(actorCard.getHeroCards(), true);
			for (CardsInfo cardsInfo : sList) {
				actorCardBuilder.addHeroCards(cardsInfo);
			}
			actorCardBuilder.setCurrentMagic(actorCard.getCurrentMagic());
			actorCardBuilder.setMaxMagic(actorCard.getMaxMagic());
			builder.addCardStone(actorCardBuilder);
		}
		
		PlayerContext cotenxt = (PlayerContext) SpringContext.getBean(PlayerContext.class);
		Response response = Response.valueOf((byte)ModuleName.Module.BATTLE_VALUE, (byte)BattleCmd.Battle.PUSH_BATTLE_DATA_VALUE, 0, builder.build().toByteArray());
		cotenxt.push(actorId, response);
		
	}
}
